package com.atguigu.guli.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.atguigu.common_utils.utils.PageUtils;
import com.atguigu.common_utils.utils.Query;
import com.atguigu.guli.edu.entity.Subject;
import com.atguigu.guli.edu.entity.Teacher;
import com.atguigu.guli.edu.entity.excel.SubjectDate;
import com.atguigu.guli.edu.excel.ExcelImportListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.atguigu.guli.edu.dao.EduSubjectDao;
import com.atguigu.guli.edu.service.EduSubjectService;
import org.springframework.web.multipart.MultipartFile;


@Service("eduSubjectService")
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectDao, Subject> implements EduSubjectService {

    @Autowired
    EduSubjectDao subjectDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<Subject> page = this.page(
                new Query<Subject>().getPage(params),
                new QueryWrapper<Subject>()
        );

        return new PageUtils(page);
    }

    @Override
    public void importFile(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream()).
                    head(SubjectDate.class).
                    sheet(0).
                    registerReadListener(new ExcelImportListener(subjectDao)).doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //二级菜单查询
    @Override
    public List<Subject> selectLevel() {
        //查询所有信息
        List<Subject> list = subjectDao.selectList(null);

        List<Subject> collect = list.stream().filter(item -> {
            return item.getParentId().equals("0");
        }).map(item -> {
            //查询一级分类下的子分类
            List<Subject> subjectList = getChildren(item, list);
            item.setChildren(subjectList);
            return item;
        }).collect(Collectors.toList());

        return collect;
    }

    //查询子分类
    private List<Subject> getChildren(Subject subject, List<Subject> list) {
        List<Subject> collect = list.stream().filter(item -> {
            return item.getParentId().equals(subject.getId());
        }).map(item -> {
            //递归查询子分类
            List<Subject> children = getChildren(item, list);
            item.setChildren(children);
            return item;
        }).collect(Collectors.toList());
        return collect;
    }

}